/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.sharding.sample.multidb.singletable.service;

import com.lvyh.lightframe.sharding.client.pagination.DefaultPageResult;
import com.lvyh.lightframe.sharding.client.pagination.PageParam;
import com.lvyh.lightframe.sharding.client.pagination.PageUtil;
import com.lvyh.lightframe.sharding.client.util.BeanUtil;
import com.lvyh.lightframe.sharding.client.util.Page;
import com.lvyh.lightframe.sharding.sample.multidb.singletable.bean.TradeUserBean;
import com.lvyh.lightframe.sharding.sample.multidb.singletable.bean.TradeUserOrderBean;
import com.lvyh.lightframe.sharding.sample.multidb.singletable.dao.entity.TradeUser;
import com.lvyh.lightframe.sharding.sample.multidb.singletable.dao.entity.TradeUserExample;
import com.lvyh.lightframe.sharding.sample.multidb.singletable.dao.entity.TradeUserOrder;
import com.lvyh.lightframe.sharding.sample.multidb.singletable.dao.entity.TradeUserOrderExample;
import com.lvyh.lightframe.sharding.sample.multidb.singletable.dao.mapper.TradeUserMapper;
import com.lvyh.lightframe.sharding.sample.multidb.singletable.dao.mapper.TradeUserOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lvyh 2021/08/01.
 */
@Service
public class ShardingMainDataService {

    private final static Logger logger = LoggerFactory.getLogger(ShardingMainDataService.class);

    @Autowired
    private TradeUserMapper tradeUserMapper;

    @Autowired
    private TradeUserOrderMapper tradeUserOrderMapper;


    public boolean deleteTradeUserOrder(Long id) throws Exception {
        if (id == null) {
            return false;
        }
        try {
            int updateNum = tradeUserOrderMapper.deleteByPrimaryKey(id);
            return updateNum == 1;
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public List<TradeUserOrderBean> selectTradeUserOrder(TradeUserOrderBean condition) throws Exception {
        List<TradeUserOrderBean> list = new ArrayList<TradeUserOrderBean>();
        try {
            TradeUserOrderExample example = new TradeUserOrderExample();
            TradeUserOrderExample.Criteria criteria = example.createCriteria();
            if (condition.getId() != null) {
                criteria.andIdEqualTo(condition.getId());
            }


            List<TradeUserOrder> queryDataItems = tradeUserOrderMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(queryDataItems)) {
                return list;
            }

            for (TradeUserOrder tradeUserOrder : queryDataItems) {
                list.add(BeanUtil.toBean(TradeUserOrderBean.class, BeanUtil.toMap(tradeUserOrder)));
            }

        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
        return list;
    }

    public DefaultPageResult<TradeUserOrderBean> selectTradeUserOrderByCondition(TradeUserOrderBean condition, PageParam pageParam) throws Exception {
        if (pageParam == null) {
            throw new Exception("pageParam must need");
        }
        Page<TradeUserOrder> page = PageUtil.startPage(pageParam);

        try {
            TradeUserOrderExample example = new TradeUserOrderExample();
            if (condition != null) {
                TradeUserOrderExample.Criteria criteria = example.createCriteria();
                if (condition.getId() != null) {
                    criteria.andIdEqualTo(condition.getId());
                }

            }

            List<TradeUserOrder> queryDataItems = tradeUserOrderMapper.selectByExample(example);
            DefaultPageResult<TradeUserOrderBean> result = new DefaultPageResult<>();
            if (queryDataItems == null || queryDataItems.size() == 0) {
                return result;
            }

            List<TradeUserOrderBean> list = new ArrayList<TradeUserOrderBean>();
            for (TradeUserOrder tradeUserOrder : queryDataItems) {
                list.add(BeanUtil.toBean(TradeUserOrderBean.class, BeanUtil.toMap(tradeUserOrder)));
            }

            result.setResultList(list);
            result.setPageSize(page.getPageSize());
            result.setPageNo(page.getPageNum());
            result.setTotalCount((int) page.getTotal());
            result.setTotalPage(page.getPages());
            return result;
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public int countTradeUserOrderByCondition(TradeUserOrderBean condition) throws Exception {
        try {
            TradeUserOrderExample example = new TradeUserOrderExample();
            if (condition != null) {
                TradeUserOrderExample.Criteria criteria = example.createCriteria();
                if (condition.getId() != null) {
                    criteria.andIdEqualTo(condition.getId());
                }


            }

            return tradeUserOrderMapper.countByExample(example);
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    @Transactional(rollbackFor = {RuntimeException.class})
    public boolean updateTradeUserOrder(TradeUserOrderBean tradeUserOrderBean) throws Exception {
        if (tradeUserOrderBean == null || tradeUserOrderBean.getId() <= 0) {
            return false;
        }
        try {
            tradeUserOrderBean.setUpdateTime(new Date());
            TradeUserOrder updateBean = BeanUtil.toBean(TradeUserOrder.class, BeanUtil.toMap(tradeUserOrderBean));
            int updateNum = tradeUserOrderMapper.updateByPrimaryKeySelective(updateBean);
            return updateNum == 1;
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public TradeUserOrderBean selectTradeUserOrderById(Long id) throws Exception {
        if (id <= 0) {
            return null;
        }
        try {
            TradeUserOrder tradeUserOrder = tradeUserOrderMapper.selectByPrimaryKey(id);
            if (tradeUserOrder == null) {
                logger.warn("not found data, tid:{}", id);
                return null;
            }
            return BeanUtil.toBean(TradeUserOrderBean.class, BeanUtil.toMap(tradeUserOrder));
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public Long saveTradeUserOrder(TradeUserOrderBean tradeUserOrderBean) throws Exception {
        if (tradeUserOrderBean == null) {
            return -1L;
        }
        try {
            tradeUserOrderBean.setCreateTime(new Date());
            tradeUserOrderBean.setUpdateTime(new Date());
            TradeUserOrder insertBean = BeanUtil.toBean(TradeUserOrder.class, BeanUtil.toMap(tradeUserOrderBean));
            tradeUserOrderMapper.insertSelective(insertBean);
            return insertBean.getId();
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public boolean deleteTradeUser(Long id) throws Exception {
        if (id == null) {
            return false;
        }
        try {
            int updateNum = tradeUserMapper.deleteByPrimaryKey(id);
            return updateNum == 1;
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public List<TradeUserBean> selectTradeUser(TradeUserBean condition) throws Exception {
        List<TradeUserBean> list = new ArrayList<TradeUserBean>();
        try {
            TradeUserExample example = new TradeUserExample();
            TradeUserExample.Criteria criteria = example.createCriteria();
            if (condition.getId() != null) {
                criteria.andIdEqualTo(condition.getId());
            }


            List<TradeUser> queryDataItems = tradeUserMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(queryDataItems)) {
                return list;
            }

            for (TradeUser tradeUser : queryDataItems) {
                list.add(BeanUtil.toBean(TradeUserBean.class, BeanUtil.toMap(tradeUser)));
            }

        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
        return list;
    }

    public DefaultPageResult<TradeUserBean> selectTradeUserByCondition(TradeUserBean condition, PageParam pageParam) throws Exception {
        if (pageParam == null) {
            throw new Exception("pageParam must need");
        }
        Page<TradeUser> page = PageUtil.startPage(pageParam);

        try {
            TradeUserExample example = new TradeUserExample();
            if (condition != null) {
                TradeUserExample.Criteria criteria = example.createCriteria();
                if (condition.getId() != null) {
                    criteria.andIdEqualTo(condition.getId());
                }

            }

            List<TradeUser> queryDataItems = tradeUserMapper.selectByExample(example);
            DefaultPageResult<TradeUserBean> result = new DefaultPageResult<>();
            if (queryDataItems == null || queryDataItems.size() == 0) {
                return result;
            }

            List<TradeUserBean> list = new ArrayList<TradeUserBean>();
            for (TradeUser tradeUser : queryDataItems) {
                list.add(BeanUtil.toBean(TradeUserBean.class, BeanUtil.toMap(tradeUser)));
            }

            result.setResultList(list);
            result.setPageSize(page.getPageSize());
            result.setPageNo(page.getPageNum());
            result.setTotalCount((int) page.getTotal());
            result.setTotalPage(page.getPages());
            return result;
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public int countTradeUserByCondition(TradeUserBean condition) throws Exception {
        try {
            TradeUserExample example = new TradeUserExample();
            if (condition != null) {
                TradeUserExample.Criteria criteria = example.createCriteria();
                if (condition.getId() != null) {
                    criteria.andIdEqualTo(condition.getId());
                }


            }

            return tradeUserMapper.countByExample(example);
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    @Transactional(rollbackFor = {RuntimeException.class})
    public boolean updateTradeUser(TradeUserBean tradeUserBean) throws Exception {
        if (tradeUserBean == null || tradeUserBean.getId() <= 0) {
            return false;
        }
        try {
            tradeUserBean.setUpdateTime(new Date());
            TradeUser updateBean = BeanUtil.toBean(TradeUser.class, BeanUtil.toMap(tradeUserBean));
            int updateNum = tradeUserMapper.updateByPrimaryKeySelective(updateBean);
            return updateNum == 1;
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    public TradeUserBean selectTradeUserById(Long id) throws Exception {
        if (id <= 0) {
            return null;
        }
        try {
            TradeUser tradeUser = tradeUserMapper.selectByPrimaryKey(id);
            if (tradeUser == null) {
                logger.warn("not found data, tid:{}", id);
                return null;
            }
            return BeanUtil.toBean(TradeUserBean.class, BeanUtil.toMap(tradeUser));
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }

    @Transactional
    public Long saveTradeUser(TradeUserBean tradeUserBean) throws Exception {
        if (tradeUserBean == null) {
            return -1L;
        }
        try {
            tradeUserBean.setCreateTime(new Date());
            tradeUserBean.setUpdateTime(new Date());
            TradeUser insertBean = BeanUtil.toBean(TradeUser.class, BeanUtil.toMap(tradeUserBean));
            tradeUserMapper.insertSelective(insertBean);
            return insertBean.getId();
        } catch (Exception exp) {
            logger.error(exp.getMessage(), exp);
            throw exp;
        }
    }
}
